package io.gitee.zhucan123.core.infrastructure.dataconversion;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * 让Jackson默认的LocalDateTime反序列化器支持时间戳
 * @author guodu
 * @date 2020/2/27
 */
public class JacksonLocalDateTimeDeserializer extends LocalDateTimeDeserializer {

  protected final ZoneId zoneId;

  public JacksonLocalDateTimeDeserializer(DateTimeFormatter formatter, ZoneId zoneId) {
    super(formatter);
    this.zoneId = zoneId;
  }

  @Override
  public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
      long tm = parser.getNumberValue().longValue();
      return LocalDateTime.ofInstant(Instant.ofEpochMilli(tm), this.zoneId);
    }
    return super.deserialize(parser, context);
  }

}
